package com.jindy.module.returnreceiptorder.service.impl;

import com.jindy.common.core.domain.entity.SysUser;
import com.jindy.common.exception.base.BaseException;
import com.jindy.common.utils.DateUtils;
import com.jindy.common.utils.SecurityUtils;
import com.jindy.jpush.domain.UniPushDomain;
import com.jindy.jpush.utils.UniJpushUtils;
import com.jindy.module.approvalConfig.domain.ApprovalConfig;
import com.jindy.module.approvalConfig.mapper.ApprovalConfigMapper;
import com.jindy.module.constant.StatusConstants;
import com.jindy.module.jpush.mapper.JpushMapper;
import com.jindy.module.machine.domain.Machine;
import com.jindy.module.machine.domain.MachineRecord;
import com.jindy.module.machine.mapper.MachineMapper;
import com.jindy.module.machine.mapper.MachineRecordMapper;
import com.jindy.module.order.domain.Order;
import com.jindy.module.order.domain.OrderProduct;
import com.jindy.module.order.mapper.OrderMapper;
import com.jindy.module.order.mapper.OrderProductMapper;
import com.jindy.module.order.service.impl.OrderServiceImpl;
import com.jindy.module.outboundorder.domain.OutboundOrder;
import com.jindy.module.outboundorder.domain.OutboundOrderMachine;
import com.jindy.module.outboundorder.mapper.OutboundOrderMachineMapper;
import com.jindy.module.outboundorder.mapper.OutboundOrderMapper;
import com.jindy.module.product.domain.ProductModel;
import com.jindy.module.product.mapper.ProductModelMapper;
import com.jindy.module.returnapplyorder.domain.ReturnApply;
import com.jindy.module.returnapplyorder.domain.ReturnApplyProduct;
import com.jindy.module.returnapplyorder.dto.ReturnApplyDto;
import com.jindy.module.returnapplyorder.mapper.ReturnApplyMapper;
import com.jindy.module.returnapplyorder.mapper.ReturnApplyProductMapper;
import com.jindy.module.returnreceiptorder.domain.ReturnReceiptOrder;
import com.jindy.module.returnreceiptorder.domain.ReturnReceiptOrderMechine;
import com.jindy.module.returnreceiptorder.domain.ReturnReceiptOrderProduct;
import com.jindy.module.returnreceiptorder.mapper.ReturnReceiptOrderMapper;
import com.jindy.module.returnreceiptorder.mapper.ReturnReceiptOrderMechineMapper;
import com.jindy.module.returnreceiptorder.service.IReturnReceiptOrderService;
import com.jindy.module.stock.domain.Stock;
import com.jindy.module.stock.mapper.StockMapper;
import com.jindy.module.warehouse.domain.Warehouse;
import com.jindy.module.warehouse.mapper.WarehouseMapper;
import com.jindy.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 回货入库单Service业务层处理
 *
 * @author ruoyi
 * @date 2022-10-19
 */
@Service
public class ReturnReceiptOrderServiceImpl implements IReturnReceiptOrderService
{
    private static final Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class);
    @Resource
    private ReturnReceiptOrderMapper returnReceiptOrderMapper;
    @Autowired
    private ISysUserService sysUserService;
    @Resource
    private ProductModelMapper productModelMapper;
    @Resource
    private StockMapper stockMapper;
    @Resource
    private ReturnApplyMapper returnApplyMapper;
    @Resource
    private OrderProductMapper orderProductMapper;
    @Resource
    private ReturnReceiptOrderMechineMapper returnReceiptOrderMechineMapper;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private MachineMapper machineMapper;
    @Resource
    private MachineRecordMapper machineRecordMapper;
    @Resource
    private OutboundOrderMapper outboundOrderMapper;
    @Resource
    private OutboundOrderMachineMapper outboundOrderMachineMapper;
    @Resource
    private ReturnApplyProductMapper returnApplyProductMapper;
    @Resource
    private WarehouseMapper warehouseMapper;

    /**
     * 消息推送设备配置
     */
    @Resource
    private JpushMapper jpushMapper;

    /**
     * 审批配置表
     */
    @Resource
    private ApprovalConfigMapper approvalConfigMapper;

    /**
     * 查询回货入库单
     *
     * @param id 回货入库单主键
     * @return 回货入库单
     */
    @Override
    public ReturnReceiptOrder selectReturnReceiptOrderById(Long id)
    {
        ReturnReceiptOrder returnApply = returnReceiptOrderMapper.selectReturnReceiptOrderById(id);
        ReturnReceiptOrderMechine mechine = new ReturnReceiptOrderMechine();
        mechine.setReceiptOrderId(returnApply.getId());
        List<ReturnReceiptOrderMechine> mechineList = returnReceiptOrderMechineMapper.selectReturnReceiptOrderMechineList(mechine);
        returnApply.setMechineList(mechineList);
        return returnApply;
    }

    /**
     * 查询回货入库单列表
     *
     * @param returnReceiptOrder 回货入库单
     * @return 回货入库单
     */
    @Override
    public List<ReturnReceiptOrder> selectReturnReceiptOrderList(ReturnReceiptOrder returnReceiptOrder)
    {
        List<ReturnReceiptOrder> list = returnReceiptOrderMapper.selectReturnReceiptOrderList(returnReceiptOrder);
        if(!CollectionUtils.isEmpty(list)){
            list.forEach(or->{
                ReturnReceiptOrderMechine mechine = new ReturnReceiptOrderMechine();
                mechine.setReceiptOrderId(or.getId());
                List<ReturnReceiptOrderMechine> mechineList = returnReceiptOrderMechineMapper.selectReturnReceiptOrderMechineList(mechine);
                or.setMechineList(mechineList);
            });
        }
        return list;
    }

    /**
     * 新增回货入库单
     *
     * @param returnReceiptOrder 回货入库单
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertReturnReceiptOrder(ReturnReceiptOrder returnReceiptOrder)
    {
        returnReceiptOrder.setCreateTime(DateUtils.getNowDate());
        SysUser sysUser = sysUserService.selectUserByUserName(SecurityUtils.getUsername());
        returnReceiptOrder.setCreateBy(sysUser.getUserName());
        returnReceiptOrder.setCreateTime(DateUtils.getNowDate());
        returnReceiptOrder.setSponsor(sysUser.getUserId());
        returnReceiptOrder.setSponsorName(sysUser.getUserName());
        returnReceiptOrder.setOrderStatus(StatusConstants.ReceiptStatusConstant.deliveryStatus_2);
        int result = returnReceiptOrderMapper.insertReturnReceiptOrder(returnReceiptOrder);
        //创建回货申请单时，提醒物流人员
        noticeLogistics(returnReceiptOrder);
        if(!CollectionUtils.isEmpty(returnReceiptOrder.getMechineList())){
            //关联产品
            returnReceiptOrder.getMechineList().forEach(mechine -> {
                mechine.setReceiptOrderId(returnReceiptOrder.getId());
            });
            returnReceiptOrderMechineMapper.insertReturnReceiptOrderMechines(returnReceiptOrder.getMechineList());
            //回货入库成功
            updateMechine(returnReceiptOrder,returnReceiptOrder.getMechineList());
        }
        return result;
    }

    /**
     * 消息通知物流人员
     * @param returnReceiptOrder
     */
    private void noticeLogistics(ReturnReceiptOrder returnReceiptOrder) {
        try {
            List<ApprovalConfig> approvalConfigList = approvalConfigMapper.selectApprovalConfigList(new ApprovalConfig("ZLDD_NB_WL", "1"));
            if (CollectionUtils.isEmpty(approvalConfigList)){
                throw new BaseException("insertReturnReceiptOrder","获取物流人员信息失败");
            }
            List<String> regIds = jpushMapper.selectRegistrationIdsByUserIds(approvalConfigList.stream().map(ApprovalConfig::getUserId).collect(Collectors.toList()));
            if (!CollectionUtils.isEmpty(regIds)){
                UniJpushUtils.doPost(new UniPushDomain(regIds,"湿云","回货入库单已创建："+ returnReceiptOrder.getReturnReceiptNo()));
            }
        } catch (Exception e) {
            LOGGER.error("回货消息通知物流人员失败",e);
        }
    }

    /**
     * 扫码新增机器回货记录
     *
     * @param machineRecord 机器回货记录
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertReturnReceiptOrder2(MachineRecord machineRecord) {
        //二维码是否为空
        if (machineRecord.getMachineNo() == null) {
            throw new RuntimeException("扫码错误，请扫描正确二维码");
        }

        //拿到登陆者信息，并查出其所负责的仓库
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Warehouse warehouse = getWarehouseByUserId(sysUser);

        //校验二维码是否存在
        Machine machine2 = new Machine();
        machine2.setMachineNo(machineRecord.getMachineNo());
        List<Machine> machineList = machineMapper.selectMachineList2(machine2);
        if (machineList.size() == 0) {
            throw new RuntimeException("此机器不存在!");
        }
        //校验机器状态是否正常(不可使用的也可以扫码入库)
        Machine machine1 = machineList.get(0);
        if ("0".equals(machine1.getStatus())) {
            throw new RuntimeException("此机器已入库，请勿重复扫码");
        } else if ("3".equals(machine1.getStatus())) {
            throw new RuntimeException("此机器未激活");
        }

        //查询机器所属未完成订单
        Order order1 = selectOrderByMachineRecord(machineRecord);

        // 1.机器添加入库记录
        MachineRecord record = new MachineRecord();
        record.setWarehousingTime(DateUtils.getNowDate());
        record.setMachineId(machine1.getId());
        record.setMachineNo(machine1.getMachineNo());
        record.setOrderNo(order1.getOrderNo());
        record.setOrderId(order1.getId());
        record.setWarehouseId(warehouse.getId());
        record.setWarehouseName(warehouse.getWarehouseName());
        record.setMachineSerialNumber(machine1.getMachineSerialNumber());

        //添加机器使用状态为状态为正常
        record.setStatus(StatusConstants.MachineRecordStatusConstant.machineRecordStatus_0);
        int result = machineRecordMapper.insertMachineRecord(record);

        // 如果机器的状态为使用中
        if("2".equals(machine1.getStatus())){//把使用中的状态改为正常，加上得到的仓库信息
            machine1.setStatus(StatusConstants.MachineStatusConstant.machineStatus_0);
            machine1.setWarehouseId(warehouse.getId());
            machine1.setWarehouseName(warehouse.getWarehouseName());
            //如果使用中的机器入库，修改库存
            checkAndUpdateStock2(machine1,warehouse);
            machineMapper.updateMachine(machine1);
        }else if("1".equals(machine1.getStatus())){//维修中的机器入库时状态不变，加上得到的仓库信息
            //如果不可用的机器入库，修改库存
            machine1.setWarehouseId(warehouse.getId());
            machine1.setWarehouseName(warehouse.getWarehouseName());
            checkAndUpdateStock1(machine1,warehouse);
            machineMapper.updateMachine(machine1);
        }

        // 3:修改产品-模型中的数量
        ProductModel productModel = new ProductModel();
        productModel.setDelFlag("0");
        productModel.setProductId(machine1.getProductId().toString());
        productModel.setProductName(machine1.getProductName());
        productModel.setModel(machine1.getModel());
        productModel = productModelMapper.selectProductModel(productModel);
        productModel.setQuantity(productModel.getQuantity() + 1);
        productModelMapper.updateProductModel(productModel);

        //5.查询订单明细
        OrderProduct orderProduct = new OrderProduct();
        orderProduct.setOrderId(order1.getId());
        orderProduct.setProductId(machine1.getProductId());
        orderProduct.setModel(machine1.getModel());
        List<OrderProduct> orderProducts = orderProductMapper.selectOrderProductList(orderProduct);
        if (!CollectionUtils.isEmpty(orderProducts)) {
            orderProduct = orderProducts.get(0);
            orderProduct.setReturnQuantity(orderProduct.getReturnQuantity() + 1L);
            orderProductMapper.updateOrderProduct(orderProduct);
        }

        //查询机器所属未完成订单,校验并添加出库机器回库申请时间
        checkAndInsertTimeQuantity(machineRecord);

        Integer returnQuantity = orderProductMapper.getReturnQuantityCount(order1.getId());
        Integer quantity = orderProductMapper.getQuantityCount(order1.getId());
        if (returnQuantity.intValue() == quantity.intValue()) {
            //6:数量和入库数量相等，修改订单的状态为入库完毕
            order1.setOrderStatus(StatusConstants.OrderStatusConstant.orderStatus_4);
            orderMapper.updateOrder(order1);
            //  通知业务员
            noticeInitiator(order1.getOrderNo());
        } else {
            //7:数量和入库数量不相等，修改订单的状态为入库中
            order1.setOrderStatus(StatusConstants.OrderStatusConstant.orderStatus_10);
            orderMapper.updateOrder(order1);
        }
        return result;
    }

    /**
     * 拿到登陆者信息，并查出其所负责的仓库
     *
     * @param sysUser 用户信息
     * @return 记录
     */
    private Warehouse getWarehouseByUserId(SysUser sysUser){
        String userId = sysUser.getUserId().toString();
        //拿到所有仓库信息
        Warehouse warehouse1 = new Warehouse();
        List<Warehouse> warehouseList1 = new ArrayList<>();
        Warehouse warehouse = new Warehouse();
        List<Warehouse> warehouseList = warehouseMapper.selectWarehouseList(warehouse);
        if(!CollectionUtils.isEmpty(warehouseList)){
            warehouseList.forEach(ware->{
                // 如果ResponsibleUser 中包含这个负责人(负责人只有一个仓库）
                if (ware.getResponsibleUser().contains(userId)) {
                    warehouseList1.add(ware);
                }
            });
        }
        //获取该负责人所属仓库
        if(!CollectionUtils.isEmpty(warehouseList1)){
            warehouse1 = warehouseList1.get(0);
        }
        return warehouse1;
    }

    /**
     * 根据机器状态修改库存
     *
     * @param machine1 机器
     * @param warehouse 仓库
     */
    void checkAndUpdateStock2 (Machine machine1,Warehouse warehouse){
        // 4:修改仓库库存
        Stock stock = new Stock();
        stock.setProductId(machine1.getProductId());
        stock.setModel(machine1.getModel());
        stock.setWarehouseId(warehouse.getId());
        List<Stock> stocks = stockMapper.selectStockList(stock);
        //如果机器所入的仓库有这个类型的机器，则库存数量+1，如果没有，则创建这一类型，其初始数量为0，现存数量为1。
        if (!CollectionUtils.isEmpty(stocks)) {
            stock = stocks.get(0);
            stock.setQuantity(stock.getQuantity() + 1);
            stock.setAvailableQuantity(stock.getAvailableQuantity() + 1);
            stockMapper.updateStock(stock);
        } else {
            Stock stock2 = new Stock();
            stock2.setProductName(machine1.getProductName());
            stock2.setProductNo(machine1.getProductNo());
            stock2.setProductId(machine1.getProductId());
            stock2.setModel(machine1.getModel());
            stock2.setQuantity(1L);
            stock2.setWarehouseId(warehouse.getId());
            stock2.setWarehouseName(warehouse.getWarehouseName());
            stock2.setAvailableQuantity(1L);
            stock2.setStartQuantity(0L);//本来没有，所以初始数量为0
            stockMapper.insertStock(stock2);
        }
    }


    /**
     * 根据机器状态修改库存
     *
     * @param machine1 机器
     * @param warehouse 仓库
     */
    void checkAndUpdateStock1 (Machine machine1,Warehouse warehouse){
        // 4:修改仓库库存
        Stock stock = new Stock();
        stock.setProductId(machine1.getProductId());
        stock.setModel(machine1.getModel());
        stock.setWarehouseId(warehouse.getId());
        List<Stock> stocks = stockMapper.selectStockList(stock);
        //如果机器所入的仓库有这个类型的机器，则库存数量+1，如果没有，则创建这一类型，其初始数量为0，现存数量为1。
        if (!CollectionUtils.isEmpty(stocks)) {
            stock = stocks.get(0);
            stock.setQuantity(stock.getQuantity() + 1);
            stockMapper.updateStock(stock);
        } else {
            Stock stock2 = new Stock();
            stock2.setProductName(machine1.getProductName());
            stock2.setProductNo(machine1.getProductNo());
            stock2.setProductId(machine1.getProductId());
            stock2.setModel(machine1.getModel());
            stock2.setQuantity(1L);
            stock2.setWarehouseId(warehouse.getId());
            stock2.setWarehouseName(warehouse.getWarehouseName());
            stock2.setStartQuantity(0L);//本来没有，所以初始数量为0
            stockMapper.insertStock(stock2);
        }
    }


    /**
     * 查询机器所属未完成订单
     *
     * @param machineRecord 记录
     * @return 记录
     */
    private Order selectOrderByMachineRecord(MachineRecord machineRecord){
        List<Order> orderList = new ArrayList<>();
        //通过传入的机器编号筛选出对应的订单（尚未入库，或入库申请中）
        MachineRecord machineRecord2 = new MachineRecord();
        machineRecord2.setMachineNo(machineRecord.getMachineNo());
        List<MachineRecord> machineRecordList = machineRecordMapper.selectMachineRecordList(machineRecord2);
        machineRecordList.forEach(machineRecord1 -> {
            if (machineRecord1.getOutboundTime() != null) {
                Order order1 = orderMapper.selectOrderById(machineRecord1.getOrderId());
                if (order1 != null) {
                    if (order1.getOrderStatus().equals("9") || order1.getOrderStatus().equals("3")) {
                        orderList.add(order1);
                    } else if (order1.getOrderStatus().equals("10")) {
                        orderList.add(order1);
                    }//此处要抛错，后续再加
                }
            }
        });

        //如果机器找不到未入库完成的租赁销售订单
        if (orderList.size() == 0) {
            throw new RuntimeException("机器编码为：" + machineRecord.getMachineNo() + " 的机器找不到租赁订单！");
        }
        Order order1 = orderList.get(0);

        return order1;
    }

    /**
     * 机器已入库通知租赁订单发起人
     *
     * @param orderNo
     */
    private void noticeInitiator(String orderNo) {
        try {
            Order order = orderMapper.selectOrderByOrderNo(orderNo);
            if (Objects.nonNull(order)) {
                List<String> userIds = jpushMapper.selectRegistrationIdsByUserIds(Collections.singletonList(order.getSponsor()));
                if (CollectionUtils.isEmpty(userIds)) {
                    throw new BaseException("已入库-通知租赁订单发起人发起人设备不存在"+order.getSponsor());
                }else{
                    UniJpushUtils.doPost(new UniPushDomain(userIds, "湿云", orderNo + "已入库"));
                }
            }else{
                throw new BaseException("已入库-通知租赁订单发起人:",orderNo+"订单不存在");
            }
        } catch (Exception e) {
            LOGGER.error("机器已入库通知租赁订单发起人失败", e);
        }
    }


    /**
     * 查询机器所属未完成订单,校验并添加出库机器回库申请时间
     *
     * @param machineRecord 记录
     * @return 记录
     */
     void checkAndInsertTimeQuantity(MachineRecord machineRecord){

         MachineRecord machineRecord1 = new MachineRecord();
         machineRecord1.setMachineNo(machineRecord.getMachineNo());
         //根据传入的值取出相应的机器记录
         List<MachineRecord> machineRecordList = machineRecordMapper.selectMachineRecordList(machineRecord1);

         List<Order> orderList = new ArrayList<>();
         List<Order> orderList2 = new ArrayList<>();
         Order order = new Order();

         if(!CollectionUtils.isEmpty(machineRecordList)){
             machineRecordList.forEach(record->{
                 if(record.getOutboundId()!= null && record.getOrderId() != null){
                     Order order1 = orderMapper.selectOrderById(record.getOrderId());
                     orderList.add(order1); } //过滤出所有存在此机器的订单
             });
         }
         if(!CollectionUtils.isEmpty(orderList)){//过滤出所有存在此机器的订单中符合要求的
             orderList.forEach(or->{
                 if(or.getOrderStatus().equals("9") || or.getOrderStatus().equals("3")) {
                     orderList2.add(or);
                 }else if(or.getOrderStatus().equals("10")){
                     orderList2.add(or);}
             });
         }

         if(orderList2.size() == 1){ //只存在一个订单为合理
             order = orderList2.get(0);
         }else { throw  new RuntimeException("此机器订单状态异常，请联系管理员"); }

         //该订单的所有回货申请单子单(returnApplyList2)
         ReturnApplyDto returnApply = new ReturnApplyDto();
         returnApply.setOrderId(order.getId());

         List<ReturnApplyDto> returnApplyList2 = new ArrayList<>();
         List<ReturnApplyDto> returnApplyList = returnApplyMapper.selectReturnApplyList(returnApply);
         if(!CollectionUtils.isEmpty(returnApplyList)){
             returnApplyList.forEach(apply->{
                 if(apply.getParentId()!= 0L){returnApplyList2.add(apply);}
             });
         }

         //通过机器编号查询机器信息
         Machine machine = new Machine();
         machine.setMachineNo(machineRecord.getMachineNo());
         Machine machine1 = machineMapper.selectMachineList2(machine).get(0);


         //该订单的所有回货申请单子单产品表中，该型号机器的数据的集合(returnApplyProductList)
         List<ReturnApplyProduct> returnApplyProductList = new ArrayList<>();
         if(!CollectionUtils.isEmpty(returnApplyList2)){
             returnApplyList2.forEach(apply->{
                 ReturnApplyProduct returnApplyProduct = new ReturnApplyProduct();
                 returnApplyProduct.setReturnApplyId(apply.getId());
                 returnApplyProduct.setModel(machine1.getModel());
                 List<ReturnApplyProduct> returnApplyProductList1 = returnApplyProductMapper.selectReturnApplyProductList(returnApplyProduct);
                 if(!CollectionUtils.isEmpty(returnApplyProductList1)){
                     ReturnApplyProduct returnApplyProduct1 = returnApplyProductList1.get(0);//该子单中这种机器类型对应的信息
                     returnApplyProductList.add(returnApplyProduct1);
                 }
             });
         }

         //查到此订单中该出库机器中这台机器数据(outboundOrderMachine)
         List<OutboundOrderMachine> outboundOrderMachineList = new ArrayList<>();
         OutboundOrder outboundOrder = new OutboundOrder();
         outboundOrder.setOrderId(order.getId());
         List<OutboundOrder> outboundOrderList2 = new ArrayList<>();//出库单子单集合
         List<OutboundOrder> outboundOrderList = outboundOrderMapper.selectOutboundOrderList(outboundOrder);
         if(!CollectionUtils.isEmpty(outboundOrderList)){
             outboundOrderList.forEach(outbound->{
                 if (outbound.getParentId() != 0L){outboundOrderList2.add(outbound);}
             });
         }
         if(!CollectionUtils.isEmpty(outboundOrderList2)){
             outboundOrderList2.forEach(outbound2->{
                 OutboundOrderMachine outboundOrderMachine2 = new OutboundOrderMachine();
                 outboundOrderMachine2.setOutboundOrderId(outbound2.getId());
                 outboundOrderMachine2.setMachineNo(machine1.getMachineNo());
                 List<OutboundOrderMachine> outboundOrderMachineList1 = outboundOrderMachineMapper.selectOutboundOrderMachineList2(outboundOrderMachine2);
                 if(!CollectionUtils.isEmpty(outboundOrderMachineList1)){
                     outboundOrderMachineList.addAll(outboundOrderMachineList1);
                 }
             });
         }
         //订单对应出库机器表中的这条数据
         OutboundOrderMachine outboundOrderMachine = outboundOrderMachineList.get(0);


         //该型号机器的数据的集合,并校验添加出库机器回货申请时间
         if(!CollectionUtils.isEmpty(returnApplyProductList)){
//             returnApplyProductList.forEach(applyProduct->{
             for(ReturnApplyProduct applyProduct:returnApplyProductList ){
                 if(applyProduct.getReturnQuantity() > applyProduct.getTimeQuantity()){
                     applyProduct.setTimeQuantity(applyProduct.getTimeQuantity()+1L);
                     returnApplyProductMapper.updateReturnApplyProduct(applyProduct);

                     //获取对应回库申请单
                     ReturnApply returnApply1 = returnApplyMapper.selectReturnApplyById(applyProduct.getReturnApplyId());
                     outboundOrderMachine.setWarehouseTime(returnApply1.getCreateTime());//等到创建时间 添加到出库机器回货申请时间
                     outboundOrderMachineMapper.updateOutboundOrderMachine(outboundOrderMachine);
                     break;
                 }
             }
//             });
         }
     }



    /**
     * 扫码查询机器所属未完成订单
     *
     * @param machineRecord 记录
     * @return 记录
     */
    @Override
    public Order selectOrderByMachineNo(MachineRecord machineRecord){//machineNo必传

        MachineRecord machineRecord1 = new MachineRecord();
        machineRecord1.setMachineNo(machineRecord.getMachineNo());
        //根据传入的值取出相应的机器记录
        List<MachineRecord> machineRecordList = machineRecordMapper.selectMachineRecordList(machineRecord1);

        List<Order> orderList = new ArrayList<>();
        List<Order> orderList2 = new ArrayList<>();
        Order order = new Order();

        if(!CollectionUtils.isEmpty(machineRecordList)){
            machineRecordList.forEach(record->{
                if(record.getOutboundId()!= null && record.getOrderId() != null){
                    Order order1 = orderMapper.selectOrderById(record.getOrderId());
                    orderList.add(order1); } //过滤出所有存在此机器的订单
            });
        }
        if(!CollectionUtils.isEmpty(orderList)){//过滤出所有存在此机器的订单中没有完结的
            orderList.forEach(or->{
                if(or.getOrderStatus().equals("9") || or.getOrderStatus().equals("3")) {
                    orderList2.add(or);
                }else if(or.getOrderStatus().equals("10")){
                    orderList2.add(or);}
            });
        }

        if(orderList2.size() == 1){ //只存在一个订单为合理
             order = orderList2.get(0);
        }else { throw  new RuntimeException("此机器订单状态异常，请联系管理员"); }

        return order;
    }

    /**
     * 回货入库成功
     * @param returnReceiptOrder
     * @param productList
     */
    void updateStock(ReturnReceiptOrder returnReceiptOrder,List<ReturnReceiptOrderProduct> productList){
        ReturnApply returnApply = returnApplyMapper.selectReturnApplyById(returnReceiptOrder.getReturnApplyId());
        Order order = orderMapper.selectOrderById(returnApply.getOrderId());
        for(ReturnReceiptOrderProduct product:productList){
            // 1:修改产品-模型中的数量
            ProductModel productModel = new ProductModel();
            BeanUtils.copyProperties(product,productModel);
            productModel = productModelMapper.selectProductModel(productModel);
            productModel.setQuantity(productModel.getQuantity()+product.getReceiptQuantity());
            productModelMapper.updateProductModel(productModel);

            // 2:修改仓库库存
            Stock stock = new Stock();
            stock.setProductId(product.getProductId());
            stock.setModel(productModel.getModel());
            stock.setWarehouseId(product.getWarehousingWarehouseId());
            List<Stock> stocks = stockMapper.selectStockList(stock);
            if(!CollectionUtils.isEmpty(stocks)){
                stock= stocks.get(0);
                stock.setQuantity(stock.getQuantity()+product.getReceiptQuantity());
                stock.setAvailableQuantity(stock.getAvailableQuantity()+product.getReceiptQuantity());
                stockMapper.updateStock(stock);
            }

            // 3:修改订单表的回货数量

            if(returnApply != null){
                //查询订单明细
                OrderProduct orderProduct = new OrderProduct();
                orderProduct.setOrderId(returnApply.getOrderId());
                orderProduct.setProductId(product.getProductId());
                orderProduct.setModel(product.getModel());
                List<OrderProduct> orderProducts = orderProductMapper.selectOrderProductList(orderProduct);
                if(!CollectionUtils.isEmpty(orderProducts)){
                    orderProduct = orderProducts.get(0);
                    orderProduct.setReturnQuantity(orderProduct.getReturnQuantity()+product.getReceiptQuantity());
                    orderProductMapper.updateOrderProduct(orderProduct);
                }
                // 4：修改申请单的状态为已完成
                returnApply.setOrderStatus(StatusConstants.ApprovalStatusConstant.approvalStatus_2);
                returnApplyMapper.updateReturnApply(returnApply);
            }
        }

    }
    /**
     * 回货入库成功
     * @param returnReceiptOrder
     * @param mechineList
     */
    void updateMechine(ReturnReceiptOrder returnReceiptOrder,List<ReturnReceiptOrderMechine> mechineList){
        // 给机器添加入库记录
        List<MachineRecord> machineRecords = new ArrayList<>();
        // 3:修改订单表的回货数量
        ReturnApply returnApply = returnApplyMapper.selectReturnApplyById(returnReceiptOrder.getReturnApplyId());
        ReturnApply parent = returnApplyMapper.selectReturnApplyById(returnApply.getParentId());
        Order order = orderMapper.selectOrderById(parent.getOrderId());
        for(ReturnReceiptOrderMechine returnReceiptOrderMechine:mechineList){
            // 1:修改产品-模型中的数量
            ProductModel productModel = new ProductModel();
            BeanUtils.copyProperties(returnReceiptOrderMechine,productModel);
            productModel.setDelFlag("0");
            productModel.setProductId(returnReceiptOrderMechine.getProductId().toString());
            productModel = productModelMapper.selectProductModel(productModel);

            productModel.setQuantity(productModel.getQuantity()+1);
            productModelMapper.updateProductModel(productModel);

            // 2:修改仓库库存
            Stock stock = new Stock();
            stock.setProductId(returnReceiptOrderMechine.getProductId());
            stock.setModel(productModel.getModel());
            stock.setWarehouseId(returnReceiptOrderMechine.getWarehouseId());
            List<Stock> stocks = stockMapper.selectStockList(stock);
            if(!CollectionUtils.isEmpty(stocks)){
                stock= stocks.get(0);
                stock.setQuantity(stock.getQuantity()+1);
                stock.setAvailableQuantity(stock.getAvailableQuantity()+1);
                stockMapper.updateStock(stock);
            }
            //查询订单明细
            OrderProduct orderProduct = new OrderProduct();
            orderProduct.setOrderId(order.getId());
            orderProduct.setProductId(returnReceiptOrderMechine.getProductId());
            orderProduct.setModel(returnReceiptOrderMechine.getModel());
            List<OrderProduct> orderProducts = orderProductMapper.selectOrderProductList(orderProduct);
            if(!CollectionUtils.isEmpty(orderProducts)){
                orderProduct = orderProducts.get(0);
                orderProduct.setReturnQuantity(orderProduct.getReturnQuantity()+1);
                orderProductMapper.updateOrderProduct(orderProduct);
            }

            //查询机器，是否回到原仓库
            Machine machine = machineMapper.selectMachineById(returnReceiptOrderMechine.getMachineId());
            if(!machine.getWarehouseId().equals(returnReceiptOrderMechine.getMachineId())){
                //机器回到了其他仓库，则修改机器的所属仓库信息
                machine.setWarehouseId(returnReceiptOrderMechine.getWarehouseId());
                machine.setWarehouseName(returnReceiptOrderMechine.getWarehouseName());
            }

            // 4.机器添加入库记录
            MachineRecord record = new MachineRecord();
            record.setWarehousingId(returnReceiptOrder.getId());
            record.setWarehousingNo(returnReceiptOrder.getReturnReceiptNo());
            record.setWarehousingTime(returnReceiptOrder.getWarehousingTime());
            record.setMachineId(returnReceiptOrderMechine.getMachineId());
            record.setMachineNo(returnReceiptOrderMechine.getMachineNo());
            record.setOrderNo(order.getOrderNo());
            record.setOrderId(order.getId());
            record.setWarehouseId(returnReceiptOrderMechine.getWarehouseId());
            record.setWarehouseName(returnReceiptOrderMechine.getWarehouseName());
            //添加机器使用状态为状态为正常
            record.setStatus(StatusConstants.MachineRecordStatusConstant.machineRecordStatus_0);
            machineRecords.add(record);

            // 5.修改机器的状态为正常
            machine.setStatus(StatusConstants.MachineStatusConstant.machineStatus_0);
            machineMapper.updateMachine(machine);

        }
        machineRecordMapper.insertMachineRecords(machineRecords);

        // 6：修改子申请单的状态为已完成
        returnApply.setOrderStatus(StatusConstants.ApprovalStatusConstant.approvalStatus_2);
        returnApplyMapper.updateReturnApply(returnApply);

        //7:如果回货入库都完成，则修改申请单主单子的状态为已入库
        if(parent.getReturnType().equals("1")){
            Integer returnQuantity = orderProductMapper.getReturnQuantityCount(order.getId());
            Integer quantity = orderProductMapper.getQuantityCount(order.getId());
            if(returnQuantity.intValue() == quantity.intValue()){
                parent.setOrderStatus(StatusConstants.ApprovalStatusConstant.approvalStatus_2);
                returnApplyMapper.updateReturnApply(parent);
                // 8:修改订单的状态为入库完毕
                order.setOrderStatus(StatusConstants.OrderStatusConstant.orderStatus_4);
                order.setWarehouseTime(DateUtils.getNowDate());
                orderMapper.updateOrder(order);
            //    通知租赁订单发起人
                List<String> regIds = jpushMapper.selectRegistrationIdsByUserIds(Collections.singletonList(order.getSponsor()));
                if (!CollectionUtils.isEmpty(regIds)){
                    UniJpushUtils.doPost(new UniPushDomain(regIds,"湿云",order.getOrderNo()+"租赁订单已入库。"));
                }
            }
        }

    }

    /**
     * 修改回货入库单
     *
     * @param returnReceiptOrder 回货入库单
     * @return 结果
     */
    @Override
    public int updateReturnReceiptOrder(ReturnReceiptOrder returnReceiptOrder)
    {
        SysUser sysUser = sysUserService.selectUserByUserName(SecurityUtils.getUsername());
        returnReceiptOrder.setUpdateBy(sysUser.getUserName());
        returnReceiptOrder.setUpdateTime(DateUtils.getNowDate());
        //删除订单关联的产品
        returnReceiptOrderMechineMapper.deleteReturnReceiptOrderMechineByOrderId(returnReceiptOrder.getId());
        if(!CollectionUtils.isEmpty(returnReceiptOrder.getMechineList())){
            //关联产品
            returnReceiptOrder.getMechineList().forEach(mechine -> {
                mechine.setReceiptOrderId(returnReceiptOrder.getId());
            });
            returnReceiptOrderMechineMapper.insertReturnReceiptOrderMechines(returnReceiptOrder.getMechineList());
        }
        return returnReceiptOrderMapper.updateReturnReceiptOrder(returnReceiptOrder);
    }

    /**
     * 批量删除回货入库单
     *
     * @param ids 需要删除的回货入库单主键
     * @return 结果
     */
    @Override
    public int deleteReturnReceiptOrderByIds(Long[] ids)
    {
        return returnReceiptOrderMapper.deleteReturnReceiptOrderByIds(ids);
    }

    /**
     * 删除回货入库单信息
     *
     * @param id 回货入库单主键
     * @return 结果
     */
    @Override
    public int deleteReturnReceiptOrderById(Long id)
    {
        return returnReceiptOrderMapper.deleteReturnReceiptOrderById(id);
    }

}
